import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MyThreadPool {
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    public MyThreadPool(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                try {
                    //保持线程持续运行
                    while (true) {
                        Runnable task = queue.take();
                        task.run();
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.setDaemon(true);
            t.start();
        }
    }

    public void submit(Runnable task) {
        try {
            queue.put(task);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(4);
        for (int i = 0; i < 1000; i++) {
            final int n = i;
            myThreadPool.submit(() -> {
                //task.run到这里
                System.out.println(Thread.currentThread().getName()+","+n);
            });
        }

        //防止主线程运行过快
        Thread.sleep(1000);
    }
    String s = "hello\0";

}
